package com.example.wwk.graduationpractice.Activity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import android.util.Log;
import android.view.View;


import android.widget.Button;
import android.widget.EditText;

import android.widget.ImageView;

import android.widget.LinearLayout;
import android.widget.TextView;


import com.example.wwk.graduationpractice.Broadcast.MessageComeBroadReceiver;
import com.example.wwk.graduationpractice.Fragment.tab_message;
import com.example.wwk.graduationpractice.NetDataUtils.LitePalUtils;
import com.example.wwk.graduationpractice.NetDataUtils.MessagesDataUtils;
import com.example.wwk.graduationpractice.Globalutils.ActivityCollector;
import com.example.wwk.graduationpractice.Globalutils.PromptShowUtils;
import com.example.wwk.graduationpractice.R;
import com.example.wwk.graduationpractice.Adapter.ChatConsultAdapter;

import com.example.wwk.graduationpractice.Bean.ChatConsultBean;

import com.example.wwk.graduationpractice.Bean.ComeMsgBean;
import com.example.wwk.graduationpractice.Bean.MessageBean;
import com.example.wwk.graduationpractice.EmotionFragment.EmotionMainFragment;
import com.example.wwk.graduationpractice.Globalutils.MyApplication;
import com.example.wwk.graduationpractice.Globalutils.TimeUtils;
import com.example.wwk.graduationpractice.Globalutils.CustomDialogUtils;

import org.jivesoftware.smack.AbstractXMPPConnection;
import org.jivesoftware.smack.SmackException;
import org.jivesoftware.smack.chat.Chat;
import org.jivesoftware.smack.chat.ChatManager;


import java.util.ArrayList;
import java.util.List;

public class ChatConsultActivity extends AppCompatActivity implements View.OnClickListener {

    //back
    private ImageView back;
    //RecyclerView 适配器以及数据显示需要的list
    private List<ChatConsultBean> chatList = new ArrayList<>();
    private List<MessageBean> messageBeanList = null;
    private RecyclerView chatRecyclerView;
    private ChatConsultAdapter adapter;
    //smack 聊天需要的连接
    private AbstractXMPPConnection connection;
    private static ChatManager chatManager;
    private static Chat chat;

    private TextView nickName;
    //handler
    private static Handler handler; //static ??
    private static final int RECEIVE_UPDATE = 1;
    private static final int SEND_CLICK = 2;
    //intent 传值
    private String thisuserName;
    private String consultantUser;
    //表情面板
    private EmotionMainFragment emotionMainFragment;
    private View rootView;
    private LinearLayout contentView;
    //进度对话框
    private CustomDialogUtils progressDialog;
    //消息接收的广播
    private MessageComeBroadReceiver messageComeBroadReceiver;
    private IntentFilter intentFilter;
    //log tag
    private static final String TAG = "123";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chat_consult);
        ActivityCollector.addActivity(this);
        setTitle("");
        //进度条
        progressDialog = new CustomDialogUtils(ChatConsultActivity.this, R.style.CustomDialog);
        progressDialog.setCancelable(false);        //无法手动取消
        progressDialog.show();
        //表情面板操作
        contentView = (LinearLayout) findViewById(R.id.chat_consult_content_view);      //要在initEmotionMainFragment前创建
        initEmotionMainFragment();
        //handler
        handler = new Handler() {       //接收发送消息的更新界面
            @Override
            public void handleMessage(final android.os.Message msg) { //处理异步消息
                super.handleMessage(msg);
                switch (msg.what) {
                    case RECEIVE_UPDATE://更新接收消息时的界面
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateList((String) msg.obj, msg.arg1);
                            }
                        });

                        break;
                    case SEND_CLICK:    //点击send按钮
                        chatSend((String) msg.obj, chat);
                        break;
                    case MessagesDataUtils.GETMSGSUCCESS:
                        messageBeanList = (List<MessageBean>) msg.obj;
                        initHistory();      //初始化历史数据
                        progressDialog.dismiss();
                        break;
                }
            }
        };

        //获取全局connection
        connection = MyApplication.getConnection();
        //intent
        Intent intent1 = getIntent();
        thisuserName = intent1.getStringExtra("thisuserName");    //获取当前用户的用户名
        consultantUser = intent1.getStringExtra("userName");    //获取咨询师的用户名
        Log.d(TAG, "chat consultantUser " + consultantUser);
        //获得历史记录
        MessagesDataUtils.getMsgs(consultantUser, thisuserName, handler);
        //聊天消息
        chatManager = ChatManager.getInstanceFor(connection);      //获取实例
        chat = chatManager.createChat(consultantUser + "@" + connection.getServiceName());   //为发送信息建立聊天通道
        //标题栏显示昵称
        nickName = (TextView) findViewById(R.id.chat_consult_nick_name);
        nickName.setText(consultantUser);
        //recyclerView的管理
        chatRecyclerView = (RecyclerView) findViewById(R.id.chat_consult_recycler_view);
        recyclerViewManager();
        //back
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
        //消息处理的广播
        messageComeBroadReceiver = new MessageComeBroadReceiver();
        intentFilter = new IntentFilter();
        intentFilter.addAction(MessageComeBroadReceiver.MSG_COME);
        registerReceiver(messageComeBroadReceiver, intentFilter);
        messageComeBroadReceiver.setDealMsgListener(new MessageComeBroadReceiver.DealMsgListener() {
            @Override
            public void deal(String from, String body) {
                if (from.equals(consultantUser)) {
                    Log.d(TAG, "chat deal: " + from + " " + body);
                    int type = ChatConsultBean.TYPE_RECEIVED;
                    android.os.Message ms = new android.os.Message();
                    ms.what = RECEIVE_UPDATE;
                    ms.arg1 = type;
                    ms.obj = body;
                    handler.sendMessage(ms);
                }

            }
        });

    }

    /*
    * 初始化历史记录
    */
    private void initHistory() {
        ChatConsultBean chatConsultBean;
        int type;
        int scrollPos = 1;      //滚动位置
        //当存在历史记录
        if (messageBeanList != null) {
            for (MessageBean msg : messageBeanList) {
                //判断消息的类型是接收还是发送
                if (consultantUser.equals(msg.getSender()))
                    type = ChatConsultBean.TYPE_RECEIVED;
                else
                    type = ChatConsultBean.TYPE_SENT;
                chatConsultBean = new ChatConsultBean(msg.getContent(), type, msg.getCreateDate());
                chatList.add(chatConsultBean);
                //通知列表更改
                adapter.notifyDataSetChanged();
                List<ComeMsgBean> comeMsgBeens = LitePalUtils.querryData(thisuserName, consultantUser);
                //存在未读消息
                if (comeMsgBeens.size() != 0) {
                    for (ComeMsgBean comeMsgBean : comeMsgBeens)
                        scrollPos = comeMsgBean.getUnreadCount();   //未读数量一定大于等于1
                }
                //设置进入聊天页面如果有未读信息则scroll到最上方未读位置
                chatRecyclerView.scrollToPosition(chatList.size() - scrollPos);
            }
        }
        //当未读信息数量超过一个页面显示的信息数量
        if (scrollPos > 6)
            PromptShowUtils.showToast("您有" + scrollPos + "条信息未读！");

    }

    /*
    *注意Fragment的生命周期
    *由于Fragment的onCreateView执行在Activity的onCreate之后，所有需要等onCreateView执行后再获得View否则会得到null,
    * 即需要在onstart中初始化emotionBoard
    */
    @Override
    public void onStart() {
        super.onStart();
        rootView = emotionMainFragment.getView();
        Button sendBtn = (Button) rootView.findViewById(R.id.bar_btn_send); //emotionBoard的发送按钮时间
        final EditText inputText = (EditText) rootView.findViewById(R.id.bar_edit_text);
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String content = inputText.getText().toString();
                android.os.Message message = new android.os.Message();
                message.what = SEND_CLICK;
                message.obj = content;
                handler.sendMessage(message);
                inputText.setText("");
            }
        });
    }

    /*
       初始化表情面板
      */
    public void initEmotionMainFragment() {
        //构建传递参数
        Bundle bundle = new Bundle();
        //绑定主内容编辑框
        bundle.putBoolean(EmotionMainFragment.BIND_TO_EDITTEXT, true);
        //隐藏控件
        bundle.putBoolean(EmotionMainFragment.HIDE_BAR_EDITTEXT_AND_BTN, false);
        //替换fragment
        //创建修改实例
        emotionMainFragment = EmotionMainFragment.newInstance(EmotionMainFragment.class, bundle);
        emotionMainFragment.bindToContentView(contentView);            //传入内容布局，即表情键盘上面的部分

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        // Replace whatever is in thefragment_container view with this fragment,
        // and add the transaction to the backstack
        transaction.replace(R.id.fl_emotionview_main, emotionMainFragment);
        transaction.addToBackStack(null);
        //提交修改
        transaction.commit();
    }

    @Override
    public void onBackPressed() {
      /*
        判断是否拦截返回键操作
       */
        if (!emotionMainFragment.isInterceptBackPress()) {
            super.onBackPressed();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(messageComeBroadReceiver);
        ActivityCollector.removeActivity(this);
    }

    /*
    recyclerView的初始化
     */
    private void recyclerViewManager() {
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);      //线性布局管理器
        chatRecyclerView.setLayoutManager(layoutManager);
        adapter = new ChatConsultAdapter(chatList);             //传入arraylist
        chatRecyclerView.setAdapter(adapter);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                Intent intent = new Intent(tab_message.DealUnreadBroadReceiver.DEAL_UNREAD);
                intent.putExtra("userJID", consultantUser + "@" + connection.getServiceName());
                sendBroadcast(intent);      //通过广播传递数据，用于处理未读消息气泡
                finish();
                break;
            default:
                break;

        }
    }

    /*
    * 消息的发送
    * @param String sendContent
    * @param Chat
    * return void
    * */
    private void chatSend(String sendContent, Chat chat) {
        if (!"".equals(sendContent)) {        //当发送的消息不为空
            try {
                chat.sendMessage(sendContent);          //发送消息
                int type = ChatConsultBean.TYPE_SENT;
                updateList(sendContent, type);      //更新显示数据
            } catch (SmackException.NotConnectedException e) {
                e.printStackTrace();
                PromptShowUtils.showToast("消息发送失败！");
            }


        }
    }

    /*
    * 更新显示数据
    * @param String content
    * @param int type
    * return void
    * */
    private void updateList(String content, int type) {
        ChatConsultBean chatConsultBean = new ChatConsultBean(content, type, TimeUtils.getTime());
        chatList.add(chatConsultBean);
        adapter.notifyDataSetChanged();
        chatRecyclerView.scrollToPosition(chatList.size() - 1);       //将list定位到最后一行

    }

}
